package com.yangyang.androidconnect.util;

import android.content.Context;
import android.os.Environment;

import com.yangyang.androidconnect.config.ProjectConfig;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;

public class ThumbnailUtil {
    private static final File workFile = Environment.getExternalStorageDirectory();

    public static String generateThumbnail(String path, Context context) throws IOException {
        File imageFile = FileUtils.getFile(path);

        String cachePath = CacheUtils.getCachePath(context);

        //.nomedia
//        File nomediaFile = FileUtils.getFile(workFile, ProjectConfig.CACHE_THUMBNAIL, ".nomedia");
//        if (!nomediaFile.getParentFile().exists()) {
//            nomediaFile.getParentFile().mkdirs();
//        }
//        if (!nomediaFile.exists()) {
//            nomediaFile.createNewFile();
//        }

        File thumbnailFile = FileUtils.getFile(cachePath, ProjectConfig.CACHE_THUMBNAIL, path);
        if (thumbnailFile.exists()) {
            return thumbnailFile.getAbsolutePath();
        }
        //生成缩略图
        if (!thumbnailFile.getParentFile().exists()) {
            thumbnailFile.getParentFile().mkdirs();
        }
        String imagePath = imageFile.getAbsolutePath();
        String outputThumbnailPath = thumbnailFile.getAbsolutePath();

        String extension = "." + FilenameUtils.getExtension(imagePath).toLowerCase();

        // 根据文件类型生成缩略图
        switch (extension) {
            case ".jpg":
            case ".jpeg":
            case ".png":
            case ".gif":
                ThumbnailGenerator.generateThumbnail(imagePath, outputThumbnailPath);
                break;
            case ".mp4":
            case ".avi":
            case ".mkv":
                VideoThumbnailUtil.createVideoThumbnail(imagePath, outputThumbnailPath);
                break;
            default:
                // 如果不是支持的扩展名，可以选择忽略或记录日志
                break;
        }

        return outputThumbnailPath;

    }
}
